<template>
  <div class="chart-settings">
    <a-form layout="vertical">
      <!-- 图表标题设置 -->
      <a-form-item label="标题">
        <a-input v-model:value="localOptions.title.text" placeholder="请输入图表标题" />
      </a-form-item>
      
      <a-form-item label="显示标题">
        <a-switch v-model:checked="localOptions.title.show" />
      </a-form-item>
      
      <!-- 雷达图指示器设置 -->
      <a-divider>雷达图指示器</a-divider>
      
      <div v-for="(indicator, index) in localOptions.radar.indicator" :key="index" class="indicator-item">
        <a-row :gutter="[16, 0]">
          <a-col :span="10">
            <a-form-item :label="`指标名称 ${index + 1}`">
              <a-input v-model:value="indicator.name" placeholder="请输入名称" @change="emitUpdate" />
            </a-form-item>
          </a-col>
          <a-col :span="10">
            <a-form-item :label="`最大值 ${index + 1}`">
              <a-input-number 
                v-model:value="indicator.max" 
                style="width: 100%"
                @change="emitUpdate"
              />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item label=" " class="delete-btn-container">
              <a-button 
                type="primary" 
                danger 
                @click="removeIndicator(index)"
                shape="circle"
              >
                <delete-outlined />
              </a-button>
            </a-form-item>
          </a-col>
        </a-row>
      </div>
      
      <a-button type="dashed" block @click="addIndicator" style="margin-bottom: 16px">
        <plus-outlined /> 添加指标
      </a-button>
      
      <!-- 雷达图形状和大小 -->
      <a-form-item label="形状">
        <a-radio-group v-model:value="localOptions.radar.shape" @change="emitUpdate">
          <a-radio-button value="polygon">多边形</a-radio-button>
          <a-radio-button value="circle">圆形</a-radio-button>
        </a-radio-group>
      </a-form-item>
      
      <a-form-item label="大小">
        <a-input-number 
          v-model:value="radarRadius"
          :min="30" 
          :max="100"
          :formatter="(value: number) => `${value}%`"
          :parser="(value: string) => Number(value.replace('%', ''))"
          style="width: 100%"
          @change="updateRadarRadius"
        />
      </a-form-item>
      
      <!-- 图例设置 -->
      <a-divider>图例设置</a-divider>
      
      <a-form-item label="显示图例">
        <a-switch v-model:checked="localOptions.legend.show" @change="emitUpdate" />
      </a-form-item>
      
      <!-- 数据系列设置 -->
      <a-divider>数据系列</a-divider>
      
      <a-collapse v-model:activeKey="activeSeriesKeys">
        <a-collapse-panel 
          v-for="(series, seriesIndex) in localOptions.series[0].data" 
          :key="'series-' + seriesIndex"
          :header="`数据系列 ${seriesIndex + 1}: ${series.name || '未命名'}`"
        >
          <a-form-item label="系列名称">
            <a-input v-model:value="series.name" placeholder="请输入系列名称" @change="emitUpdate" />
          </a-form-item>
          
          <div v-for="(indicator, indicatorIndex) in localOptions.radar.indicator" :key="indicatorIndex">
            <a-form-item :label="`${indicator.name || '指标' + (indicatorIndex + 1)} 的值`">
              <a-input-number
                :value="getSeriesValue(seriesIndex, indicatorIndex)"
                style="width: 100%"
                :min="0"
                :max="indicator.max"
                @change="(value: number) => updateSeriesValue(seriesIndex, indicatorIndex, value)"
              />
            </a-form-item>
          </div>
          
          <a-form-item label="区域颜色">
            <a-input 
              v-model:value="series.itemStyle.color" 
              placeholder="如: #1890ff" 
              :addon-before="'颜色'"
              @change="emitUpdate"
            />
          </a-form-item>
          
          <a-form-item label="区域透明度">
            <a-slider 
              v-model:value="series.areaStyle.opacity" 
              :min="0" 
              :max="1" 
              :step="0.1"
              @change="emitUpdate"
            />
          </a-form-item>
          
          <a-form-item label="线条宽度">
            <a-input-number 
              v-model:value="series.lineStyle.width" 
              :min="1" 
              :max="10"
              @change="emitUpdate"
            />
          </a-form-item>
        </a-collapse-panel>
      </a-collapse>
      
      <a-divider></a-divider>
      
      <a-button type="dashed" block @click="addSeries">
        <plus-outlined /> 添加数据系列
      </a-button>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons-vue';

const props = defineProps({
  options: {
    type: Object,
    required: true
  }
});

const emit = defineEmits(['update:options']);

// 本地存储options，用于编辑
const localOptions = ref<any>({
  title: {
    text: '',
    show: false
  },
  tooltip: {},
  legend: {
    show: true,
    data: ['预算分配', '实际开销']
  },
  radar: {
    shape: 'polygon',
    radius: '75%',
    indicator: [
      { name: '销售', max: 6500 },
      { name: '管理', max: 16000 },
      { name: '信息技术', max: 30000 },
      { name: '客服', max: 38000 },
      { name: '研发', max: 52000 },
      { name: '市场', max: 25000 }
    ]
  },
  series: [{
    name: '预算 vs 开销',
    type: 'radar',
    data: [
      {
        value: [4300, 10000, 28000, 35000, 50000, 19000],
        name: '预算分配',
        areaStyle: { opacity: 0.5 },
        lineStyle: { width: 2 },
        itemStyle: { color: '#5470c6' }
      },
      {
        value: [5000, 14000, 28000, 31000, 42000, 21000],
        name: '实际开销',
        areaStyle: { opacity: 0.5 },
        lineStyle: { width: 2 },
        itemStyle: { color: '#91cc75' }
      }
    ]
  }]
});

// 用于Collapse的活动面板
const activeSeriesKeys = ref<string[]>(['series-0']);

// 雷达图半径
const radarRadius = ref(75);

// 更新雷达图半径
const updateRadarRadius = () => {
  localOptions.value.radar.radius = `${radarRadius.value}%`;
  emitUpdate();
};

// 获取系列指标值
const getSeriesValue = (seriesIndex: number, indicatorIndex: number) => {
  const series = localOptions.value.series[0].data[seriesIndex];
  if (!series.value) {
    series.value = Array(localOptions.value.radar.indicator.length).fill(0);
  } else if (series.value.length <= indicatorIndex) {
    // 扩展数组
    series.value = [...series.value, ...Array(indicatorIndex - series.value.length + 1).fill(0)];
  }
  
  return series.value[indicatorIndex];
};

// 更新系列指标值
const updateSeriesValue = (seriesIndex: number, indicatorIndex: number, value: number) => {
  const series = localOptions.value.series[0].data[seriesIndex];
  if (!series.value) {
    series.value = Array(localOptions.value.radar.indicator.length).fill(0);
  }
  
  // 确保数组长度足够
  while (series.value.length <= indicatorIndex) {
    series.value.push(0);
  }
  
  series.value[indicatorIndex] = value;
  emitUpdate();
};

// 添加指标
const addIndicator = () => {
  localOptions.value.radar.indicator.push({
    name: `新指标${localOptions.value.radar.indicator.length + 1}`,
    max: 10000
  });
  
  // 更新所有系列的value数组长度
  localOptions.value.series[0].data.forEach((series: any) => {
    if (!series.value) {
      series.value = Array(localOptions.value.radar.indicator.length).fill(0);
    } else {
      series.value.push(0);
    }
  });
  
  emitUpdate();
};

// 移除指标
const removeIndicator = (index: number) => {
  localOptions.value.radar.indicator.splice(index, 1);
  
  // 更新所有系列的value数组
  localOptions.value.series[0].data.forEach((series: any) => {
    if (series.value && series.value.length > index) {
      series.value.splice(index, 1);
    }
  });
  
  emitUpdate();
};

// 添加数据系列
const addSeries = () => {
  const newIndex = localOptions.value.series[0].data.length;
  const color = getRandomColor();
  
  // 创建与雷达图指标数量相同的数据点
  const indicatorCount = localOptions.value.radar.indicator.length;
  
  localOptions.value.series[0].data.push({
    name: `系列${newIndex + 1}`,
    value: Array(indicatorCount).fill(0),
    areaStyle: { opacity: 0.5 },
    lineStyle: { width: 2 },
    itemStyle: { color }
  });
  
  // 更新图例数据
  if (localOptions.value.legend && localOptions.value.legend.data) {
    localOptions.value.legend.data.push(`系列${newIndex + 1}`);
  }
  
  // 添加新系列到激活的keys
  activeSeriesKeys.value.push(`series-${newIndex}`);
  
  emitUpdate();
};

// 生成随机颜色
const getRandomColor = () => {
  const colors = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4'];
  return colors[Math.floor(Math.random() * colors.length)];
};

// 向父组件发送更新的options
const emitUpdate = () => {
  emit('update:options', localOptions.value);
};

// 初始化
onMounted(() => {
  // 深拷贝props的options
  if (props.options) {
    localOptions.value = JSON.parse(JSON.stringify(props.options));
    
    // 确保必要的属性存在
    if (!localOptions.value.title) {
      localOptions.value.title = { text: '', show: false };
    }
    
    if (!localOptions.value.legend) {
      localOptions.value.legend = { show: true, data: [] };
    } else if (!localOptions.value.legend.data) {
      localOptions.value.legend.data = [];
    }
    
    if (!localOptions.value.radar) {
      localOptions.value.radar = { 
        shape: 'polygon',
        radius: '75%',
        indicator: [
          { name: '指标1', max: 10000 }
        ]
      };
    }
    
    if (!localOptions.value.series || !localOptions.value.series.length) {
      localOptions.value.series = [{
        name: '数据系列',
        type: 'radar',
        data: [
          {
            name: '系列1',
            value: [0],
            areaStyle: { opacity: 0.5 },
            lineStyle: { width: 2 },
            itemStyle: { color: '#5470c6' }
          }
        ]
      }];
    } else {
      // 确保数据系列有必要的属性
      if (!localOptions.value.series[0].data) {
        localOptions.value.series[0].data = [];
      }
      
      localOptions.value.series[0].data.forEach((item: any) => {
        if (!item.areaStyle) item.areaStyle = { opacity: 0.5 };
        if (!item.lineStyle) item.lineStyle = { width: 2 };
        if (!item.itemStyle) item.itemStyle = { color: getRandomColor() };
        if (!item.value) item.value = Array(localOptions.value.radar.indicator.length).fill(0);
      });
    }
    
    // 初始化雷达图半径
    const radius = localOptions.value.radar.radius;
    if (typeof radius === 'string' && radius.endsWith('%')) {
      radarRadius.value = parseInt(radius, 10);
    } else {
      radarRadius.value = 75;
    }
  }
});

// 监听props.options变化
watch(() => props.options, (newOptions) => {
  if (newOptions) {
    localOptions.value = JSON.parse(JSON.stringify(newOptions));
    
    // 更新雷达图半径
    const radius = localOptions.value.radar.radius;
    if (typeof radius === 'string' && radius.endsWith('%')) {
      radarRadius.value = parseInt(radius, 10);
    } else {
      radarRadius.value = 75;
    }
  }
}, { deep: true });
</script>

<style scoped>
.chart-settings {
  padding: 10px;
}

.indicator-item {
  padding: 10px;
  margin-bottom: 12px;
  border: 1px dashed #ddd;
  border-radius: 4px;
}

.delete-btn-container {
  display: flex;
  justify-content: center;
  align-items: flex-end;
  height: 100%;
}
</style> 